#include <httplib.h>
#if defined (__linux__) || defined (__APPLE__)
#   include <unistd.h>
#elif defined (_WIN32) || defined (_WIN64)
#   include <windows.h>
#endif
#include <easylog.h>
#include "detect.hh"

namespace cloud
{

class entry
{
public:
    entry()
    {}

    void run()
    {
        _detector.run();
    }

#if defined (__linux__) || defined (__APPLE__)
    static void daemonize()
    {
        int id = fork();

        if (id < 0)
            easylog::fatal("daemonize fork failed");
        else if (id > 0)
            exit(0);

        if (setsid() < 0)
            easylog::fatal("daemonize setsid failed");

        umask(00);

        // if (chdir("/") < 0)
        //     easylog::fatal("daemonize chdir failed");

        close(0);
        // close(1);
        close(2);
    }
public:
    static void set_logger()
    {
        easylog::logger_builder::ptr llb =
            std::make_shared<easylog::local_logger_builder>();
        llb->build_logger_name("default");
        llb->build_logger_type(easylog::logger_type::async);
        llb->build_limit_level(easylog::level_enum::info);
        llb->build_sinker<easylog::file_sinker>();
        llb->build_work_type(easylog::worker_type::safe);
        llb->build_thread_num(1);
        llb->build_buffer_size();
        llb->build_buffer_increment();
        llb->build_buffer_threshold();
        easylog::logger::ptr lgr = llb->build();
        lgr->set_always_flush();
        //lgr->set_flush_every(easylog::time_enum::t2sec);
        easylog::add(lgr);
    }

#elif defined (_WIN32) || defined (_WIN64)
    static void daemonize() {}
    static void set_logger() {}
#endif

private:
    detector _detector;
};

}

int main()
{
    /* cloud::entry::daemonize(); */
    /* cloud::entry::set_logger(); */

    cloud::entry().run();

    return 0;
}
